<template>
  <!--  菜单模块页面-->
  <div class="page">

    <div class="page_main">
      <el-button icon="el-icon-plus" @click="handleAdd({})" class="common_btn-small">添加一级菜单</el-button>
      <!-- table -->
      <el-table
        :data="tableList"
        row-key="id"
        :tree-props="{children: 'subMenu', hasChildren: 'hasChildren'}"
        border>
        <el-table-column
          prop="name"
          label="菜单名称">
        </el-table-column>
        <el-table-column
          prop="url"
          label="URL">
        </el-table-column>
        <el-table-column
          prop="type"
          label="图标">
          <template slot-scope="scope">
            <i class="iconfont" :class="scope.row.menuIcon"></i>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述">
        </el-table-column>
        <el-table-column
          prop="weight"
          label="权重">
        </el-table-column>
        <el-table-column
          width="170"
          label="更新时间">
          <template slot-scope="scope">{{scope.row.updateTime | formatTimer}}</template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="240">
          <template slot-scope="scope">
            <button type="text"
                    class="btn_edit"
                    @click="handleEdit(scope.row, scope.row._level)">
              修改
            </button>
            <el-popconfirm title="确定删除该菜单吗？" @confirm="handleDelete(scope.row.id)">
              <button class="btn_delete" slot="reference">刪除</button>
            </el-popconfirm>

            <button
              class="btn_edit m-l-16"
              v-if="scope.row._level === 1 && !scope.row.url"
              @click="handleAdd(scope.row, 2)">
              <!-- level 2 代表是子集 -->
              添加子菜单
            </button>
            <button
              class="m-l-16" type="primary"
              v-if="scope.row._level === 2 && scope.row.url"
              @click="handleAdd(scope.row, 3)">
              <!-- level 3 代表是增删改查菜单 -->
              添加权限控制
            </button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增编辑弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="isShowDialog"
      width="600px">
      <!-- 具体form表单 -->
      <el-form label-position="right" ref="form" :rules="rules" :model="form" label-width="80px" class="form_width-200">
        <el-form-item label="上级菜单" v-if="form.parentId">
          <div class="width_200">{{form.__parentName}}</div>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="输入菜单名称" :maxlength="20"></el-input>
        </el-form-item>
        <!-- 添加子集时才是必填 -->
        <!-- 若是一级菜单修改，并且用子集时 禁止修改 -->
        <el-form-item label="URL" :prop="form._level === 2 ? 'url' : ''">
          <el-input v-model.trim="form.url" placeholder="输入URL" :maxlength="50"
                    :disabled="form.subMenu && form.subMenu.length && form._level === 1"></el-input>
        </el-form-item>
        <el-form-item label="菜单图标" prop="menuIcon" class="menu_icon">
          <span class="menu_icon-wrap flex-center">
            <i class="iconfont" :class="form.menuIcon"></i>
          </span>
          <el-select class="menu_icon-select" v-model.trim="form.menuIcon" filterable placeholder="菜单图标">
            <el-option :value="item.font_class" v-for="item in iconList" :key="item.font_class">
              <i style="float: left" class="iconfont" :class="item.font_class"></i>
              <span style="float: right">{{ item.font_class }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="打开方式" prop="tabFlag">
          <el-select v-model.trim="form.tabFlag" placeholder="请选择打开方式">
            <el-option
              v-for="item in EnumSysFlagList"
              :key="item.code"
              :label="item.name"
              :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model.trim="form.description" type="textarea" placeholder="描述" :maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="许可标识" v-if="form._level === 3">
          <el-input v-model.trim="form.permission" placeholder="菜单权限标识,eg sys:syslog:view"></el-input>
        </el-form-item>
        <el-form-item label="排序值">
          <el-input v-model.trim="form.weight" placeholder="值越大越靠前" type="number"></el-input>
        </el-form-item>
      </el-form>
      <!-- 操作按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isShowDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {menuUpdate, menuAdd, menuDelete} from '@/services/model/authority-mgmt'
import {getMenuTree} from '@/services/model/user'
import {getDictData} from '@/services/model/common'
import {glyphs} from '@/assets/icon-font/iconfont.json'
import Format from '@/utils/format'

// form表单校验规则

const RULES = {
  name: {required: true, message: '请输入菜单名称'},
  url: {required: true, message: '请输入URL'},
  menuIcon: {required: true, message: '请选择图标', trigger: 'change'},
  tabFlag: {required: true, message: '请打开方式', trigger: 'change'},
}

export default {
  data() {
    return {
      // 替换字段
      defaultProps: {
        children: 'subMenu',
        label: 'name'
      },
      // 表单
      form: {},
      rules: RULES,
      // 展示弹窗
      isShowDialog: false,
      // 图标列表
      iconList: [],
      // 接口获取 打开方式
      EnumSysFlagList: [],
    }
  },
  filters: {
    // 时间格式化
    formatTimer(timer) {
      return Format(new Date(timer))
    }
  },
  computed: {
    // 树形菜单
    tableList() {
      let menu = this.$store.state.nodeList
      // 设置层级
      const _setLevel = (list, index = 1) => list.map(x => {
        x._level = index
        x.subMenu && _setLevel(x.subMenu, index + 1)
        return x
      })
      return _setLevel(menu)
    },
    // 弹窗的title
    dialogTitle() {
      return this.form.id ? '编辑菜单' : '新增菜单'
    }
  },
  created() {
    this.iconList = glyphs.map(x => ({...x, font_class: 'icon' + x.font_class}))
  },
  mounted() {
    this.queryDictData()
  },
  methods: {
    // 通用获取枚举方法
    async queryDictData() {
      const {data} = await getDictData({enumName: 'EnumMenuTabFlag'})
      this.EnumSysFlagList = data || []
    },
    async handleDelete(id) {
      await menuDelete({id})
      this.$notify({
        title: '提示',
        message: '删除成功',
        type: 'success'
      })
      this.queryList()
    },
    // 添加菜单 level当前数据对应的tree层级
    handleAdd(item, level) {
      // console.log(level)
      this.form = {
        parentId: item.id,
        __parentName: item.name,
        tabFlag: this.EnumSysFlagList[0]?.code,
        _level: level
      }
      this.isShowDialog = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 编辑 level 当前操作对象相对于tree的层级
    handleEdit(item, level) {
      this.form = JSON.parse(JSON.stringify(item))
      this.form._level = level
      this.isShowDialog = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 表单提交
    validateForm() {
      this.$refs.form.validate((valid) => {
        valid && this.submitData()
      })
    },
    // 新增编辑提交数据
    async submitData() {
      // 根据ID判断使用新增还是编辑
      const AJAX_ACTION = this.form.id ? menuUpdate : menuAdd
      await AJAX_ACTION(this.form)
      this.$notify({
        type: 'success',
        title: '提示',
        message: this.form.id ? '编辑成功' : '添加成功'
      })
      this.isShowDialog = false
      this.queryList()
    },
    // 数据查询
    async queryList() {
      const {data} = await getMenuTree()
      this.$store.commit('setState', {name: 'nodeList', value: data || []})
    }
  }
}
</script>
<style lang="less" scoped>
  /deep/ .el-table {
    .cell {
      text-align: left !important;
    }
  }

  .page {
    height: 100%;
    padding: 24px;

    .menu_icon-wrap {
      vertical-align: middle;
      display: inline-flex;
      width: 40px;
      height: 40px;
      border: 1px solid #DCDFE6;
      border-top-left-radius: 4px;
      border-bottom-left-radius: 4px;
      border-right: none;

      i {
        font-size: 22px;
      }
    }

    .menu_icon-select {
      width: calc(100% - 40px);

      /deep/ input {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
        vertical-align: middle;
      }
    }

    .page_top {
      font-weight: 600;
      font-size: 20px;
      color: #23252C;
      background-color: #ffffff;
      height: 50px;
      padding: 0 20px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      margin-bottom: 16px;
    }
  }

  .page_header {
    padding: 10px 40px;
    background-color: #EEF4FF;
    color: #6680C1;

    & > em {
      padding-left: 20px;
    }

    .page_header-wrap {
      width: 70vw;
      display: flex;

      & > div {
        padding-left: 20px;
      }
    }
  }

  /deep/ .menu_tree {
    padding: 0 40px 40px;
    border-radius: 8px;

    .el-tree-node__content {
      height: 40px;
      border-bottom: 1px solid #3cc891;
    }

    .menu_node {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .menu_node-label {
        // width: 300px;
        // flex-shrink: 0;
      }

      .menu_node-content {
        display: flex;
        width: 70vw;
      }
    }
  }
</style>
